from system.object import Object
from system.eventServer import eventServer

class Fsm(Object):
    def __init__(self, parent, forwardEvents, type = None, name = None):
        Object.__init__(self,parent,type,name)
        
        self.defaultVar("state","idle")
        
        self.forward("start",{})
        
        self.forwardEvents = forwardEvents
        
        for event in self.forwardEvents:
            eventServer.register(event,self.forward)
            
    def forward(self, cmd, args):
        funcName = "%s_%s" % (cmd,self.getVar("state"))
        if hasattr(self,funcName) and callable(getattr(self,funcName)):
            getattr(self,funcName)(cmd,args)
            
    def transition(self, newState):
        if newState != self.getVar("state"):
            self.forward("end",{})
            self.setVar("state",newState)
            self.forward("start",{})
